import json
import os
from datetime import datetime

import requests

DIR=os.path.dirname(os.path.abspath(__file__))
class AuthManager:
    def __init__(self):
        self.base_url = "https://console.yjproject.chinamcloud.cn"
        self.cookie_file=DIR+'/auth_cookie.json'
        self.session = requests.Session()
        self.student_base_url="https://classroom.yjproject.chinamcloud.cn"

    def login(self):
        login_data = {
          "group_code": "",
          "login_type": "mobile_password",
          "login_mode": 1,
          "ras_pwd": "BrMCKkjgX2jpKrYxGKH2rlSax/y5blRqnWvhugAyYxgprMYLIj6Boio0Hby7nqr1v2zgFcpdeq97sUXKaeh2zL5UGmWwfyrQL4jSEPILbKwZx7ReNfREnIG524iXzi1TfDUMcKWgx8an/+JVWHBh5BlJU5cjusxmu5/w4Bf63LE=",
          "captcha_drive": "false",
          "validate": "",
          "user_mobile": "19141013603"
        }
        student_login_data = {
          "account": "st001",
          "password": "oFoecTdMgJMdKaJxAIiVP22JTa0SQ5lQOIOWL4aFGjtVWVmjPtXSTeaJm5nJQ6j9dUEWUH4VLXD9n0BU/xPExdbsfk8Fj0doZedVOrMH06r+zpChhTTXEQPUUcH/XEHVV9W+jtwi8DuTe3PaR4ifG0gN6V92knlKe61RjrednnayVyBR513x04gPRwePZN7fOE9/JTGv9TFIPZ6WxXGl4L9uYm2rj25LfITptuZGDlFRY7mLpW1QEKX+OYjzipgkeJcSmVqg1cCV0KCSr5rdqN914eGelDJxxgSy/KrAHMlkO4uzDnH1CzRRghisSeJM5npnuumjuk+nEeuXz6w6QA==",
          "code": "c2wz",
          "tenant_id": 21,
          "token": "6wdDQ4uyR7iInUffAzOtzg=="
        }
        response = self.session.post(f"{self.base_url}/login/lr/login/multi-tenant-login", json=login_data)
        student_response=self.session.post(f"{self.student_base_url}/userapi/v1/login", json=student_login_data)
        print(response.text)
        print(student_response.text)

        if response.status_code == 200:
            self._save_cookies()
            return True
        return False

    def _save_cookies(self):
        cookie_data = {
            'cookies': requests.utils.dict_from_cookiejar(self.session.cookies),
            'save_at': datetime.now().isoformat(),
            'base_url': self.base_url
        }

        with open(self.cookie_file, 'w') as f:
            json.dump(cookie_data,f,indent=2)

    def load_cookies(self):
        if not(os.path.exists(self.cookie_file)):
            return False
        with open(self.cookie_file, 'r') as f:
            cookie_data = json.load(f)
        self.session.cookies = requests.utils.dict_from_cookiejar(cookie_data['cookies'])
        return True

    def is_logged_in(self):
        response = self.session.get(f"{self.base_url}/api/")
        return response.status_code == 200

    def access_protected_page(self,endpoint):
        if not self.is_logged_in():
            if not self.load_cookies() or not self.is_logged_in():
                raise Exception("需要重新登录")
        return self.session.get(f"{self.base_url}{endpoint}")


if __name__ == '__main__':
    au=AuthManager()
    au.login()